#pragma once

#include "../ConnectionLibrary.h"

#include "SocketReaderWriter.h"

#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>

namespace AlgoTrading
{
	namespace ConnectionLibrary
	{

		class ClientConnectionsManager;

		class ClientConnectionHandler : public ClientNotificationProcessor, public SocketNotificationHandler, public std::tr1::enable_shared_from_this<ClientConnectionHandler>
		{
		public:
			ClientConnectionHandler(boost::asio::io_service& io_service, std::auto_ptr<boost::asio::ip::tcp::socket>& socket, ClientConnectionAcceptorPtr acceptor, ClientConnectionsManager& connectionsManager);
			virtual ~ClientConnectionHandler(void);

			virtual void ParseMessageData(std::istream& stream);
			virtual void OnError(const boost::system::error_code& error);
			virtual void OnDisconnect();

			void Start();
			void Stop();

			void SetRequestProcessor(ClientRequestProcessorPtr requestProcessor);

			virtual void SendNotification(const AlgoTrading::Messages::NotificationMessage&);
			virtual void SendRequestResponse(const AlgoTrading::Messages::RequestResponse&);

		private:
			std::auto_ptr<boost::asio::ip::tcp::socket> socket;
			ClientRequestProcessorPtr clientRequestProcessor;

			boost::asio::io_service& io_service;

			boost::shared_ptr<SocketReaderWriter> socketReaderWriter;

			ClientConnectionAcceptorPtr connectionAcceptor;
			ClientConnectionsManager& connectionsManager;
		};

		typedef std::tr1::shared_ptr<ClientConnectionHandler> ClientConnectionHandlerPtr;

	}
}